import os
import yaml
from typing import Dict, Any

class Config:
    _instance = None
    _config = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super(Config, cls).__new__(cls)
        return cls._instance

    def __init__(self):
        if self._config is None:
            self.load_config()

    def load_config(self, config_path: str = None) -> None:
        """
        加载配置文件
        :param config_path: 配置文件路径，默认为项目根目录下的 config.yml
        """
        if config_path is None:
            # 获取项目根目录
            root_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
            config_path = os.path.join(root_dir, 'config.yml')

        with open(config_path, 'r', encoding='utf-8') as f:
            self._config = yaml.safe_load(f)

    def get(self, key: str, default: Any = None) -> Any:
        """
        获取配置项
        :param key: 配置键，支持点号分隔的多级键，如 'redis.host'
        :param default: 默认值
        :return: 配置值
        """
        if self._config is None:
            self.load_config()

        keys = key.split('.')
        value = self._config
        for k in keys:
            if isinstance(value, dict):
                value = value.get(k, default)
            else:
                return default
        return value

    @property
    def config(self) -> Dict:
        """
        获取完整配置
        :return: 配置字典
        """
        if self._config is None:
            self.load_config()
        return self._config